<template>
  <div>
    <div class="mask" @click="closePopup(false)"></div>
    <div v-loading="loading" class="edit_box message_box">
      <div class="box_head">
        <p>{{ messageId ? '修改' : '新增' }}消息</p>
        <i @click="closePopup(false)"></i>
      </div>
      <div class="box_body">

        <div :class="{'error_border':tip_num==='title'}" class="line">
          <span class="lab"><i class="mark_icon">*</i>标题：</span>
          <div>
            <el-input v-model.trim="formData.title" placeholder="请输入标题" type="text"
                      @input="setTip('','')"></el-input>
          </div>
        </div>

        <div :class="{'error_border':tip_num==='subTitle'}" class="line">
          <span class="lab"><i class="mark_icon">*</i>副标题：</span>
          <div>
            <el-input v-model.trim="formData.subTitle" placeholder="请输入副标题" type="text"
                      @input="setTip('','')"></el-input>
          </div>
        </div>

        <div class="line" :class="{'error_border':tip_num==='photoUrl'}">
          <span class="lab"><i class="mark_icon">*</i>封面图：</span>
          <div>
            <el-upload
              :data="param"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="avatarSuccess"
              :before-upload="avatarUpload">
              <img v-if="formData.photoUrl" :src="formData.photoUrl" class="avatar">
              <i class="el-icon-plus avatar-uploader-icon" v-else></i>
            </el-upload>
          </div>
        </div>


        <div :class="{'error_border':tip_num==='content'}" class="editor_box">
          <span class="lab"><i class="mark_icon">*</i>内容：</span>
          <div>
            <div ref="editor" style="text-align:left;max-width: 800px;padding:10px;">
            </div>
          </div>
        </div>

        <div class="line" :class="{'error_border':tip_num==='sendTime'}">
          <span class="lab"><i class="mark_icon">*</i>发送日期：</span>
          <div>
            <el-date-picker
              v-model="date"
              format="yyyy- MM - dd"
              placeholder="选择日期"
              type="date"
              value-format="yyyy-MM-dd">
            </el-date-picker>
          </div>
        </div>

        <div class="line" :class="{'error_border':tip_num==='sendTime'}">
          <span class="lab"><i class="mark_icon">*</i>发送日期：</span>
          <div>
            <el-time-picker
              v-model="time"
              placeholder="请选择时间"
              value-format="HH:mm:ss">
            </el-time-picker>
          </div>
        </div>

        <div class="line" :class="{'error_border':tip_num==='noticeType'}">
          <span class="lab"><i class="mark_icon">*</i>类型：</span>
          <div>
            <el-radio-group v-model="formData.noticeType">
              <!--              <el-radio :label="1">群发</el-radio>-->
              <el-radio :label="1">单发</el-radio>
            </el-radio-group>
          </div>
        </div>

        <template v-if="formData.noticeType === 1 && isUser" :class="{'error_border':tip_num==='userId'}">
          <div class="line">
            <span class="lab"><i class="mark_icon">*</i>单选用户：</span>
            <userSelect :uId="formData.userId" :defaultId="defaultId" @listenToUser="getUserId"/>
          </div>
        </template>

        <p class="error_line">{{ infoTip }}</p>
      </div>
      <div class="box_foot">
        <span @click="closePopup(false)">取消</span>
        <span @click="confirmEdit">确定</span>
      </div>
    </div>
  </div>
</template>

<script>
import {getDetail, addData, updateData} from "@/api/data/wechat/notice";
import {restUrl} from "../../../../url";
import userSelect from '../../../components/user/index.vue';
// 富文本
import E from 'wangeditor'

export default {
  components: {
    userSelect
  },
  props: ['messageId'],
  data() {
    return {
      param: {folder: 'web/productType'},
      uploadUrl: restUrl + '/common/upload',
      formData: {
        title: '',
        subTitle: '',
        noticeType: 1,
        content: '',
        sendTime: '',
        photoUrl: '',
        userId: '',
        url: 'http://192.168.0.149:8188/message'
      },
      infoTip: '',
      tip_num: '',
      loading: false,
      date: '',
      time: '',
      isUser:false,
      defaultId:''
    }
  },
  mounted() {

    this.$nextTick(() => {
      this.initEditor();
      if (this.messageId) {
        this.getDetail();
      }
      setTimeout(()=> {
        this.isUser = true;
      },600)
    })

  },
  methods: {
    initEditor() {
      //富文本
      this.editor = new E(this.$refs.editor)
      //menu设置
      this.editor.config.menus = [
        "head",
        "bold",
        "fontSize",
        "fontName",
        "italic",
        "underline",
        "strikeThrough",
        "foreColor",
        "backColor",
        "link",
        "list",
        "justify",
        "quote",
        "emoticon",
        "image",
        "table",
        "code",
        "video",
        "undo",
        "redo"
      ];

      //图片上传
      this.editor.config.showLinkImg = true
      this.editor.config.uploadImgShowBase64 = false;
      this.editor.config.uploadImgServer = this.uploadUrl
      this.editor.config.uploadImgParams = this.param
      this.editor.config.uploadImgMaxSize = 10 * 1024 * 1024; // 将图片大小限制为 3M
      this.editor.config.uploadImgMaxLength = 5;
      this.editor.config.uploadFileName = 'file'
      this.editor.config.uploadImgHooks = {
        // 图片上传并返回结果，但图片插入错误时触发
        fail: function (xhr, editor, result) {
        },
        success: function (xhr, editor, result) {
        },
        customInsert: (insertImg, result, editor) => {
          insertImg(result.data);
        }
      };
      this.editor.config.onchange = html => {
        this.formData.content = html;
        this.$emit("onEditor", this.formData.content);
      };

      this.editor.create();
      //插入视频
      // this.editor.txt.html('<iframe src="https://bpic.588ku.com/video_listen/588ku_video/21/04/07/16/13/33/video606d69add8977.mp4"></iframe>')
    },
    getDetail() {
      let that = this;
      that.loading = true;
      getDetail(that.messageId).then(res => {
        if (res) {
          this.time = res.sendTime.split(' ')[1];
          this.date = res.sendTime.split(' ')[0]
          that.formData = res;
          this.defaultId = res.userId;
          that.editor.txt.html(res.content)

          //重置defaultId
          setTimeout(()=> {
            this.defaultId = ''
          },500)
        }
        that.loading = false;
      }).catch((e) => {
        that.loading = false;
      });
    },
    // 上传图标
    avatarUpload(file) {
      this.setTip('', '');
      this.loading = true;
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        this.$message.error({
          message: '上传图像大小不能超过 10MB!',
          duration: 1500
        });
      }
      return isLt10M;
    },

    // 图标上传回调
    avatarSuccess(res, file) {
      if (file.response.success) {
        this.formData.photoUrl = file.response.data;
        this.$message.success({
          message: '上传成功！',
          duration: 1500
        });
      } else {
        this.$message.error({
          message: '上传失败，请重试',
          duration: 1500
        });
      }
      this.loading = false;
    },


    //获取单选人ID
    getUserId(e) {
      this.formData.userId = e;
    },

    // 确认编辑
    confirmEdit() {
      this.formData.sendTime = this.date + ' ' + this.time;
      let errData = {
        title: '请输入标题！',
        subTitle: '请输入副标题！',
        photoUrl: '请上传封面图！',
        content: '请输入内容！',
        sendTime: '请选择发送时间！',
        userId: '请选择用户！',
      }
      for (let key in errData) {
        if (this.formData[key] === '' || this.formData[key] === ' ') {
          this.setTip(key,errData[key]);
          return;
        } else {
          if (key === 'userId') {
            this.sendInfo();
          }
        }
      }
    },

    sendInfo() {
      let that = this;
      that.loading = true;
      if (that.messageId) {
        updateData(this.formData).then(response => {
          that.closePopup(true);
          that.$message.success({
            message: '操作成功！',
            duration: 1500
          });
          that.loading = false;
        }).catch((e) => {
          that.loading = false;
        });
      } else {
        addData(this.formData).then(response => {
          that.closePopup(true);
          that.$message.success({
            message: '操作成功！',
            duration: 1500
          });
          that.loading = false;
        }).catch((e) => {
          that.loading = false;
        });
      }
    },

    setTip(num, text) {
      this.tip_num = num;
      this.infoTip = text
    },

    // 关闭
    closePopup(refresh) {
      this.$emit('listenToChild', {refresh: refresh})
    }
  }
}
</script>

<style scoped>
.message_box {
  width: 750px !important;
}

/*编辑框*/
.line .lab {
  width: 100px !important;
}

.editor_box {
  text-align: left;
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.editor_box .lab {
  display: inline-block;
  width: 120px;
  font-size: 16px;
  color: #000;
  text-align: right;
  padding-right: 8px;
}

.line div {
  display: inline-block;
  width: 330px;
  word-wrap: break-word
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #60BAE7;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #DCDFE6;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 1px solid #DCDFE6;
  border-radius: 6px;
}

.avatar {
  max-width: 210px;
  min-width: 60px;
  height: 100px;
  display: block;
  border-radius: 6px;
  margin-right: 15px;
  border: 1px solid #bbb;
}


</style>
